"use strict";

var C = require('../common'),
    unzip = require('unzip2'),
    path = require('path');

module.exports = {

    type: 'prepare',

    load: function (owner, config, cb) {

        config.path || C.throwRequired('[' + owner.stack + '].publish.path');

        var publicDir = owner.ensureAbsPath(config.path),
            targetRelPath = path.join(owner.app.documentRoot, owner.path),
            targetDir = owner.app.toAbsPath(targetRelPath);

        if (C.fs.existsSync(publicDir)) {
            C.fs.copySync(publicDir, targetDir);
            owner.console('Published module public files to: ' + targetRelPath);
        }

        if (config.libs) {
            var publicLibDir = path.join(owner.app.nodeframeRoot, 'public_libs'),
                targetLibDir = path.join(targetDir, 'libs');

            var libs = config.libs;
            if (C._.isString(libs)) {
                var lib = {};
                lib[libs] = libs;
                libs = lib;
            }

            C._.each(libs, function (destlib, srclib) {
                var src = path.join(publicLibDir, srclib + '.zip');
                var dest = path.join(targetLibDir, destlib);

                C.fs.createReadStream(src).pipe(unzip.Extract({ path: dest }));

                owner.console('Installed public lib: ' + lib);
            });
        }

        cb();
    }
};